<?php
namespace Managers;
use \Site\Users as UsersEntity;

class Users extends BaseManager{
    public function getAll(){
        return $this->getEntityManager()
                ->createQueryBuilder()
                ->select('n')
                ->from('Site\Users', 'n')
                ->orderBy('n.id', '')
                ->getQuery()
                ->getResult();
    }

    public function getOne($id){
        return $this->getEntityManager()
                ->createQueryBuilder()
                ->select('n')
                ->from('Site\Users', 'n')
                ->where('n.id = :id')
                ->getQuery()
                ->setParameters(array('id'=>$id))
                ->getSingleResult();
    }

    public function ValidEmail($email){
        try {
        $user =  $this->getEntityManager()
                ->createQueryBuilder()
                ->select('n')
                ->from('Site\Users', 'n')
                ->where('n.email = :email')
                ->getQuery()
                ->setParameters(array('email'=>$email))
                ->getSingleResult();
                
        //if(!empty($user->getId())) return true;
            return $user->getId();
         } catch (\Doctrine\ORM\NoResultException $e) {
            return NULL;
         }
         
    }

     public function AddUser($array){
        $entity = new UsersEntity();
        $entity->setEmail($array['email']);
        $entity->setPassword(md5($array['password']));
        $em = $this->getEntityManager();
        $em->persist($entity);
        $em->flush();
        
       return $entity->getId();
     }

     public function getUser($email, $password) {
        try {
            $user_name = $this->getEntityManager()
                    ->createQueryBuilder()
                    ->select('n')
                    ->from('Site\Users', 'n')
                    ->where('n.email = :email')
                    ->getQuery()
                    ->setParameters(array('email' => $email))
                    ->getSingleResult();

        } catch (\Doctrine\ORM\NoResultException $e) {
            return NULL;
        }
        if(($email==$user_name->getEmail())&&($password==$user_name->getPassword())) return array('id'=>$user_name->getId(),'password'=>$user_name->getPassword());
        else return NULL;
    }
    
}
